import React, { useState } from 'react';
import { Button, List, Typography, Empty, Drawer } from 'antd';
import { PlusOutlined, MessageOutlined, DeleteOutlined, EditOutlined } from '@ant-design/icons';
import { useConversationStore } from '../../../stores/conversation.store';
import { useBreakpoint } from '../../../hooks/useBreakpoint';
import './style.css';

const { Text } = Typography;

// 独立的对话项组件，可以安全使用 Hooks
const ConversationItem: React.FC<{
  conversation: any;
  isActive: boolean;
  isMobile: boolean;
  onSelect: (id: string) => void;
  onDelete: (id: string, e?: React.MouseEvent) => void;
  onLongPress: (id: string) => void;
}> = ({ conversation, isActive, isMobile, onSelect, onDelete, onLongPress }) => {
  const [touchStart, setTouchStart] = useState<number>(0);
  const [touchTimer, setTouchTimer] = useState<NodeJS.Timeout | null>(null);

  const handleTouchStart = () => {
    const startTime = Date.now();
    setTouchStart(startTime);

    const timer = setTimeout(() => {
      if (isMobile) {
        onLongPress(conversation.id);
      }
    }, 500);

    setTouchTimer(timer);
  };

  const handleTouchEnd = () => {
    if (touchTimer) {
      clearTimeout(touchTimer);
      setTouchTimer(null);
    }

    const touchDuration = Date.now() - touchStart;
    if (touchDuration < 500) {
      // 短按，执行选择
      onSelect(conversation.id);
    }
  };

  const handleTouchCancel = () => {
    if (touchTimer) {
      clearTimeout(touchTimer);
      setTouchTimer(null);
    }
  };

  return (
    <List.Item
      key={conversation.id}
      className={`conversation-item ${isActive ? 'active' : ''} ${isMobile ? 'mobile' : ''}`}
      onClick={() => !isMobile && onSelect(conversation.id)}
      onTouchStart={isMobile ? handleTouchStart : undefined}
      onTouchEnd={isMobile ? handleTouchEnd : undefined}
      onTouchCancel={isMobile ? handleTouchCancel : undefined}
      style={{
        minHeight: isMobile ? '48px' : undefined,
        padding: isMobile ? '12px 16px' : undefined
      }}
    >
      <div className="conversation-item-content">
        <MessageOutlined className="conversation-icon" />
        <div className="conversation-info">
          <Text ellipsis className="conversation-item-title">
            {conversation.title || '新对话'}
          </Text>
          <Text type="secondary" className="conversation-item-preview">
            {conversation.preview || '点击开始对话'}
          </Text>
        </div>
        {!isMobile && (
          <Button
            type="text"
            size="small"
            icon={<DeleteOutlined />}
            className="conversation-delete-btn"
            onClick={(e) => onDelete(conversation.id, e)}
          />
        )}
      </div>
    </List.Item>
  );
};

const ConversationSidebar: React.FC = () => {
  const breakpoint = useBreakpoint();
  const isMobile = breakpoint === 'mobile';

  const [showMobileMenu, setShowMobileMenu] = useState(false);
  const [selectedConvId, setSelectedConvId] = useState<string | null>(null);

  const {
    conversations,
    currentConversationId,
    createNewConversation,
    selectConversation,
    deleteConversation,
    renameConversation
  } = useConversationStore();

  const handleNewConversation = () => {
    createNewConversation();
  };

  const handleSelectConversation = (id: string) => {
    selectConversation(id);
  };

  const handleDeleteConversation = (id: string, e?: React.MouseEvent) => {
    if (e) {
      e.stopPropagation();
    }
    deleteConversation(id);
    setShowMobileMenu(false);
  };

  const handleRenameConversation = (id: string) => {
    const newTitle = prompt('输入新的对话标题');
    if (newTitle) {
      renameConversation(id, newTitle);
    }
    setShowMobileMenu(false);
  };

  const handleLongPress = (id: string) => {
    setSelectedConvId(id);
    setShowMobileMenu(true);
  };

  const menuItems = [
    {
      key: 'rename',
      label: '重命名',
      icon: <EditOutlined />,
      onClick: () => selectedConvId && handleRenameConversation(selectedConvId),
    },
    {
      key: 'delete',
      label: '删除',
      icon: <DeleteOutlined />,
      onClick: () => selectedConvId && handleDeleteConversation(selectedConvId),
      danger: true,
    },
  ];

  return (
    <div className="conversation-sidebar-container">
      <div className="sidebar-header">
        <Button
          type="primary"
          icon={<PlusOutlined />}
          block
          onClick={handleNewConversation}
          className={isMobile ? 'h-touch' : ''}
          style={{ minHeight: isMobile ? '44px' : undefined }}
        >
          新建对话
        </Button>
      </div>

      <div className="sidebar-conversations">
        {conversations.length === 0 ? (
          <Empty
            description="暂无对话记录"
            image={Empty.PRESENTED_IMAGE_SIMPLE}
          />
        ) : (
          <List
            dataSource={conversations}
            renderItem={(conversation) => (
              <ConversationItem
                key={conversation.id}
                conversation={conversation}
                isActive={conversation.id === currentConversationId}
                isMobile={isMobile}
                onSelect={handleSelectConversation}
                onDelete={handleDeleteConversation}
                onLongPress={handleLongPress}
              />
            )}
          />
        )}
      </div>

      {/* 移动端长按菜单 */}
      {isMobile && (
        <Drawer
          placement="bottom"
          open={showMobileMenu}
          onClose={() => setShowMobileMenu(false)}
          height="auto"
          closable={false}
          styles={{ body: { padding: 0 } }}
        >
          <List
            dataSource={menuItems}
            renderItem={(item: any) => (
              <List.Item
                onClick={item.onClick}
                className={`sidebar-menu-item ${item.danger ? 'danger' : ''}`}
                style={{
                  minHeight: '56px',
                  cursor: 'pointer',
                  padding: '16px 24px'
                }}
              >
                <List.Item.Meta
                  avatar={item.icon}
                  title={
                    <span style={{
                      fontSize: '16px',
                      color: item.danger ? '#ff4d4f' : undefined
                    }}>
                      {item.label}
                    </span>
                  }
                />
              </List.Item>
            )}
          />
        </Drawer>
      )}
    </div>
  );
};

export default ConversationSidebar;